<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS Excel</title>
</head>

<body>
    <button id="export">导出Excel</button>
    <br />
    <br />
    导入文件<input type="file" id="import">
    <div id="content"></div>
</body>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
<script src="https://unpkg.com/xlsx@0.13.3/dist/xlsx.full.min.js"></script>
<script src="https://cdn.bootcss.com/FileSaver.js/2014-11-29/FileSaver.js"></script>
<script>
    $(function () {

        //生成Excel导出
        function exportExcel(dataArr) {
            var ws = XLSX.utils.json_to_sheet(dataArr);
            var wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "sheet1");
            XLSX.writeFile(wb, "demo.xlsx");
        }

        //解析Excel
        function analysistExcel(data) {
            var result = [];
            var workbook = XLSX.read(data, {
                type: 'binary'
            });
            workbook.SheetNames.forEach(function (sheetName) {
                var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
                result = XL_row_object;
            })
            return result;
        }

        $('#export').on('click', function () {
            let dataArr = [];
            for (let i = 0; i < 10; i++) {
                dataArr.push({
                    '序号': '' + i,
                    '名字': 'jjss',
                    '性别': '男',
                    '年龄': '25'
                });
            }
            exportExcel(dataArr)
        })

        $('#import').on('change', function (evt) {
            var selectedFile = evt.target.files[0];
            var reader = new FileReader();
            reader.onload = function (event) {
                var data = event.target.result;
                var ret = analysistExcel(data);
                console.log(ret)
                $('#content').html(JSON.stringify(ret))
            };
            reader.onerror = function (event) {
                console.error("File could not be read! Code " + event.target.error.code);
            };
            // 读取上传文件为二进制
            reader.readAsBinaryString(selectedFile);
        })
    })
</script>

</html>